from flask_restful import Resource, fields, marshal_with, request
import view.common as view_common
import service.web_service as service
import service.generate_data_service as generate_service
from exception.api_exception import APIException
from utils.common.jwt_middleware import all_jwt_required


class GenerateData(Resource):
    """
    生成数据-基础数据-权重和方案一起生成
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @marshal_with(res_obj)
    @all_jwt_required()
    def post(self):
        try:
            data = request.get_json()
            work_order_id = int(data.get("work_order_id"))
        except Exception as e:
            raise APIException(message="解析参数错误" + str(e))
        res = generate_service.generate_data(work_order_id, data)
        return view_common.success(res=res)


class SaveBaseConfig(Resource):
    """
    保存策略
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @marshal_with(res_obj)
    @all_jwt_required()
    def post(self):
        data = request.get_json()
        if data is None:
            return view_common.failed_10001(res="保存失败，内容为空")
        wo_id = data.get('work_order_id')  # 工单id
        weights = data.get('config')  # 具体策略数据
        res = generate_service.save_programme_weight(wo_id, weights)
        return view_common.success(res=res)


class SearchBaseConfig(Resource):
    """
    查询策略
    """
    res_obj = {
        'code': fields.Integer,
        'message': fields.String,
        'result': fields.Raw
    }

    @marshal_with(res_obj)
    @all_jwt_required()
    def get(self):
        data = request.args
        work_order_id_str = data.get("work_order_id")
        if work_order_id_str is None or work_order_id_str == "":
            return view_common.failed_10001(res={"工单不存在"})
        work_order_id = int(work_order_id_str)
        load_type = data.get("load_type")
        link = data.get("link")
        res = generate_service.search_programme_from_redis(work_order_id, load_type, link)
        return view_common.success(res=res)
